<template>
    <div>
        <div class="conatianer water-container">
            <div class="top-row-aa">
                <div class="black-icon">
                    <router-link to="/water-list">
                        <svg data-v-4049f3d8="" aria-hidden="true" class="icon fanhui">
                            <use data-v-4049f3d8="" xlink:href="#icon-fanhui1"></use>
                        </svg>
                    </router-link>
                </div>


                <!-- <div class="category-icon">
                <router-link to="/shuiqing/water-detail-2">
                    <img lazy-load src="@/static/image/category-icon.png" />
                </router-link>
            </div> -->
                <div class="title-group-1">
                    <i class="el-icon-arrow-left left-icon"></i>
                    <div class="title-text" @click="popup_show = true">
                        <div>{{ params.name }}水位过程线</div>
                        <div>{{ date_str_format2.start }} 至 </br> {{ date_str_format2.end }}</div>
                    </div>
                    <i class="el-icon-arrow-right right-icon"></i>
                </div>

                <div class="clock-icon" @click="popup_show = true">
                    <img lazy-load src="@/static/image/clock-icon.png" />
                </div>
            </div>
            <graph-chart ref="graphRef" :chart_data="chart_data"></graph-chart>


            <div>
                <table class="water-info-table">
                    <tr>
                        <td><label>最新时间:</label><span>{{newDateTime}}</span></td>
                        <td><label>最新水位:</label><span>{{list[0]?.val}}米</span></td>
                    </tr>
                    <tr>
                        <td><label>汛限水位:</label><span>{{params.max}} 米</span></td>
                        <td><label>校核水位:</label><span> - -</span></td>
                    </tr>
                    <tr>
                        <td><label>最高水位:</label><span>{{chart_data.series.max()}} 米</span></td>
                        <td><label>最高时间:</label><span>13日12时45分</span></td>
                    </tr>
                    <tr>
                        <td><label>最低水位:</label><span>{{chart_data.series.min()}}米</span></td>
                        <td><label>最低时间:</label><span>13日06时55分</span></td>
                    </tr>
                </table>
            </div>

            <div>
                <el-table class="table-list" :data="list" height="450" border style="width: 100%">
                    <el-table-column prop="date" label="时间" width="170">
                    </el-table-column>
                    <el-table-column align="center" label="水位(米)">
                        <template slot-scope="scope">
                            <span>{{scope.row.val?scope.row.val:'- -'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="库容(万方)">
                        <template slot-scope="scope">
                            <span>{{scope.row.value?scope.row.value:'- -'}}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <vant-calendar :vdate="from.date" @dateRes="CalendarDate" @close="popup_show = false"
                :popup_show="popup_show"></vant-calendar>

        </div>

    </div>
</template>

<script>
    import { getWaterStorageData } from './water-storage/water-storage'  //用于库容
    import GraphChart from './echartsC/graph.vue'  //echarts组件化，避免代码太多
    import { getWaterLevelByHour } from '@/api/apiList'
    import VantCalendar from './VantCalendar/VantCalendar.vue'
    import toChartData from '@/utils/hoursToList'
    import dayjs from 'dayjs'
    import { cubicSplineInterpolation } from '@/api/math'


    function format_date(dateObj) {
        return dateObj.getFullYear() + "-" + (dateObj.getMonth() + 1) + "-" + (dateObj.getDate());
    }

    function format_date2(dateObj) {
        return dateObj.getFullYear() + "年" + (dateObj.getMonth() + 1) + "月" + (dateObj.getDate()) + "日" + dateObj.getHours() + "时" + dateObj.getMinutes() + "分";
    }

    function due_hourslist(list = []) {
        const list3 = []
        list.map(item => {
            for (let i = 0; i < 24; i++) {
                if (item['h' + i] === 0) {
                    continue
                }
                let item2 = { hour: i, val: item['h' + i], date: item['the_day'].substring(0, 10) + ' ' + i + ':00' }
                list3.push(item2)
            }
        })
        return list3
    }

    export default {
        components: { GraphChart: GraphChart, VantCalendar },
        data() {
            const getDateTimeList = (days = 5) => {
                var today = new Date();
                var date = new Date(today.getTime() - days * 24 * 60 * 60 * 1000); // 获取当前日期和时间  
                var dateTimeList = [];

                for (var i = 0; i < days * 24 * 3; i++) {
                    let arr = { 'date_str': date.toISOString().slice(0, 19).replace("T", " "), "water_level": i + 1, "capacity": "12.65" };
                    dateTimeList.push(arr); // 将日期时间格式化为ISO 8601格式，并去掉毫秒和时区部分  
                    date.setMinutes(date.getMinutes() + 20); // 增加20分钟  
                }

                return dateTimeList
            }

            var now_date = new Date();
            var pass_date = new Date();
            pass_date.setDate(now_date.getDate() - 5);

            return {
                resList: [],
                list: [],
                params: { "region": "", "name": "", "tag": "" },
                from: { date: [pass_date, now_date] },
                chart_data: { x: [], series: [], maxList: [] },
                waterStorage: [],
                popup_show: false,
                waterStorageXY: { x: [], y: [] },
                storeSigin: {
                    min: 0,
                    max: 0,
                    agv: 0,
                    resAgv: 0
                }
            }
        },
        created() {
            this.initData();
        },
        mounted() {
            //this.getWater();
        },
        computed: {
            date_str_format() {
                var start = format_date(this.from.date[0]);
                var end = format_date(this.from.date[1]);
                return { start, end }
            },
            date_str_format2() {
                var start = format_date2(this.from.date[0]);
                var end = format_date2(this.from.date[1]);
                return {
                    start, end
                }
            },
            newDateTime() {
                if (!this.resList.length) { return null }
                const last = this.resList[this.resList.length - 1];
                let date = new Date(last.the_day);
                return dayjs(date).format('D日');
            },
        },
        methods: {
            com_storage(val) {
                if (!this.waterStorage) {
                    return null
                }
                let num = cubicSplineInterpolation(val, this.waterStorageXY.y, this.waterStorageXY.x);
                if (num) {
                    num = num.toFixed(2)
                }

                return num;
            },
            /**
             * 自定义日期选择组件 基于vant
             * @param {*} val {start,end}
             */
            CalendarDate(val) {
                this.from.date = [val.start, val.end];
                this.getWater();
            },
            async getWater() {
                var [device, startTime, endTime] = [this.params.device, format_date(this.from.date[0]), format_date(this.from.date[1])];
                var res = await getWaterLevelByHour(device, startTime, endTime);



                this.resList = res.data;
                this.list = due_hourslist(res.data);
                this.list.reverse();

                // 计算平均值
                var Htotal = this.list.reduce(function (a, b) {
                    a = (typeof a == 'object') ? 0 : a;
                    return (Number(a) + Number(b.val)).toFixed(2)
                });
                this.storeSigin.resAgv = Htotal / this.list.length;
                this.storeSigin.s = (this.storeSigin.agv - this.storeSigin.resAgv).toFixed(1)

                this.chart_data = toChartData(this.resList, this.params.max);
                //加入库容曲线

                if (this.waterStorage) {
                    this.list = this.list.map(item => {
                        let height = (Number(item.val) + Number(this.storeSigin.s)).toFixed(1);
                        return Object.assign(item, { "val": height, "value": this.com_storage(height) })
                    });
                    this.chart_data.series = this.chart_data.series.map(item=>(Number(item)+Number(this.storeSigin.s)).toFixed(1))
                }
              
                this.$nextTick(() => { this.$refs.graphRef.resetChart(); });
            },
            initData() {
                this.params = this.$route.query;
                let name = this.$route.query.name;
                this.waterStorage = getWaterStorageData(name);

                if (this.waterStorage) {
                    var total = 0;
                    this.waterStorage.map(item => {
                        this.waterStorageXY.y.push(item.height);
                        this.waterStorageXY.x.push(item.value);
                        total = total + item.height;
                    });
                    const min = this.waterStorageXY.y[0];
                    const max = this.waterStorageXY.y[this.waterStorageXY.y.length - 1];
                    const agv = total / this.waterStorageXY.y.length;
                    this.storeSigin = {
                        agv,
                        min,
                        max,
                        s: max - agv,
                        resAgv: 0
                    }
                }
                this.getWater();
            }
        },

    }
</script>

<style>
    @import url("./water-detail.css");
</style>